<style scoped>
  .page-infinite-wrapper {
    background: #e3e3e3;
    padding-top: 5px;
  }
  .weui-form-preview {
    margin: 5px;
    border-radius: 5px;
  }

  .rj-cell-child {
    display: inline-block;
    font-size: 0;
    padding: 5px 15px;
    text-align: left;
  }
  .rj-cell-child.max span{
    font-size: 16px;
    padding-right: 20px;
  }
  .rj-cell-child label {
    color: #333;
    font-size: 14px;
  }
  .rj-cell-child span {
    padding-left: 20px;
    font-size: 14px;
    color: #333;
  }
  .rj-cell-child .tip {
    font-size: 16px;
    color: #333;
  }
  .rj-cell-child i {
    font-size: 18px;
    font-style: normal;
    color: #333;
  }
  .weui-form-preview__ft .weui-form-preview {
    background: #f5f5ef;
  }
  .weui-form-preview__ft {
    line-height: normal;
  }
  .weui-form-preview {
    background-color: #fff;
    margin: 5px;
    border-radius: 5px;
  }
  .weui-form-preview__hd label, .weui-form-preview__hd em {
    font-size: .9em !important;
  }
  .weui-panel__bd {
    text-align: left;
  }
  .hoverbar {
    background: #03A9F4;
    position: fixed;
    bottom: 100px;
    right: 20px;
    height: 50px;
    line-height: 50px;
    width: 50px;
    z-index: 100;
    font-size: 30px;
    border-radius: 50%;
    box-shadow: 0px 2px 3px rgba(100, 100, 100, 0.5);
    color: #fff;
  }
  .weui-cell {
    padding: 5px 15px;
  }
  .weui-label {
    text-align: left;
  }
  .page-infinite-wrapper {
    overflow-y: auto;
  }
  .itit {
    font-size: 12px;
    padding: 5px;
    border-bottom: 0.5px solid #ddd;
    margin-bottom: 5px;
  }
  .rj-cell-child {
    display: block;
  }
  .rj-cell-child p{
    padding: 3px 0;
  }
  .weui-media-box {
    padding: 0;
  }
  .attachimg {
    width: 30px;
  }
</style>

<template>
  <div class="comon">
    <div style="height: 50px; line-height: 50px; background: #f7f7f7; text-align: center; font-size: 16px; border-bottom: 1px solid #bdbbbc; position: relative">
      田检记录
      <a href="javascript:;" @click="$router.push({name: 'OrderList'})" style="position: absolute; left: 10px; top: 8px">
        <img src="@/assets/back.png" style="width: 20px" />
      </a>
    </div>
    <div class="hoverbar" v-show="showAddbtn" @click="addItem">+</div>
        <div class="tops">
          <div class="cellgroup">
            <div class="weui-cell">
              <div class="weui-cell__hd"><label class="weui-label">所属部门</label></div>
              <div class="weui-cell__bd">
                <input type="text" class="weui-input" :value="order.department" readonly />
              </div>
            </div>
            <div class="weui-cell">
              <div class="weui-cell__hd"><label class="weui-label">种植户</label></div>
              <div class="weui-cell__bd">
                <input type="text" class="weui-input" name="entity.farmername" :value="order.farmer" readonly />
              </div>
            </div>
            <div class="weui-cell">
              <div class="weui-cell__hd"><label class="weui-label">订单号</label></div>
              <div class="weui-cell__bd">
                <input type="text" class="weui-input" name="entity.ordercode" :value="order.code" readonly />
              </div>
            </div>
            <div class="weui-cell weui-cell_select">
              <div class="weui-cell__hd"><label class="weui-label">地块</label></div>
              <div class="weui-cell__bd">
                <input type="hidden" name="entity.arealandname" :value="arealand.name" />
                <input type="hidden" name="entity.arealandid" :value="arealand.guid" />
                <select class="weui-select" v-model="arealand" style="padding-left: 0;">
                  <option value="">请选择地块</option>
                  <option v-for="(item, index) in arealands" :key="item.guid" :value="item">{{item.aName}} {{item.AForests}}亩</option>
                </select>
                <p style="font-size: 12px;text-align: left;margin-right: 10px">{{arealand.AAddress}} {{arealand.ADtaddress}}</p>
              </div>
            </div>
          </div>
          <div class="page-infinite-wrapper" ref="wrapper" :style="{ height: wrapperHeight + 'px' }" >
            <div class="weui-form-preview" v-for="(item, index) in records" :key="item.guid" :ref="item.guid">
              <div class="weui-form-preview__hd">
                <label class="weui-form-preview__label" style="color: #333;">{{item.plckname}}</label>
                <em class="weui-form-preview__value" style="font-size: 14px;color:#06ae56;" @click="delItem(item.guid)">{{item.operatorid == userid ? '删除' : '&nbsp;'}}</em>
              </div>
              <div class="weui-form-preview__bd">

                <div class="weui-form-preview__item">
                  <label class="weui-form-preview__label">距地块</label>
                  <span class="weui-form-preview__value">{{item.distance}} km</span>
                </div>
                <div class="weui-form-preview__item">
                  <label class="weui-form-preview__label">田检人</label>
                  <span class="weui-form-preview__value">{{item.operator}}</span>
                </div>
                <div class="weui-form-preview__item">
                  <label class="weui-form-preview__label">田检时间</label>
                  <span class="weui-form-preview__value">{{item.createtime}}</span>
                </div>
                <div class="weui-cell" v-if="item.imgs && item.imgs.length > 0">
                  <div class="weui-cell__hd"><label class="weui-label"></label></div>
                  <div class="weui-cell__bd">
                    <div class="weui-media-box weui-media-box_text uploaderFiles">
                      <div class="exp uploaderFiles" style="display: inline-block;">
                        <img class="attachimg" style="padding-right: 5px;"  v-for="(image, index) in item.imgs" :key="image.guid"  alt="" onerror="javascript:this.src='../../../static/image/default.png';this.onerror = null" :src="image.url + '-suolue.png'" :data-img="image.url + '.png'" />
                      </div>
                    </div>
                  </div>
                </div>
                <div class="weui-form-preview__ft olist">
                  <div class="weui-panel__bd">
                    <div class="weui-form-preview">
                      <div class="rj-cell-child" v-for="(product, index) in packItems(item.items)">
                        <p class="itit">{{product.tit}}</p>
                        <p  v-for="(ii, index) in product.list">
                          <label>{{ii.plckitemname}} {{ii.plckitemname.indexOf('率') > -1 ? '(%)' : ''}}：</label><span>{{ii.plckresult}} </span>
                        </p>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            </div>
        </div>
      </div>
</template>

<script type="text/babel">
  import MescrollVue from 'mescroll.js/mescroll.vue'
  export default {
    name: 'CheckRecord',
    components: {MescrollVue},
    data() {
      return {
        wrapperHeight: 600,
        id: '',
        userid: localStorage.userid,
        postParams: {
        },
        data: [],
        order: '',
        arealands: [],
        arealand: '',
        records: [],
        plcks: [],
        existPlcks: [],
        addperms: false
      }
    },
    created() {
      this.id = this.$route.query.id;
      this.getPermission()
      //列表页头部不允许滑动
      document.getElementsByTagName("body")[0].className="bg";
    },
    mounted() {
      this.wrapperHeight = document.documentElement.clientHeight - this.$refs.wrapper.getBoundingClientRect().top - 40;

      this.getPlcks();

      $('.tops').on('click', '.uploaderFiles .attachimg', function () {
        var num = $(this).parent().children().not( ".exp" ).length;
        var imgArr = [];
        for (var i=0; i<num; i++) {
          imgArr.push($(this).parent().find('.attachimg').eq(i).data('img'));
        }
        var pnum = $(this).parent().find('.exp').length;
        var index = pnum > 0 ? $(this).index() - pnum : $(this).index();
        var pb = $.photoBrowser({
          items: imgArr,
          initIndex: index
        });
        pb.open();
      });
    },
    watch: {
      arealand: function (val) {
        this.getRecords(this.order.guid, val.guid);
      }
    },
    computed: {
      showAddbtn: function () {
        return this.addperms && (this.plcks.length - this.existPlcks.length > 0);
      }
    },
    methods: {
      getPermission: async function() {
        await this.getArealands();
        var that = this;
        this.axios({
          method: 'get',
          params:{opttype:24},
          url: '/produce/OperatorPermission!getOperPerm.action',
        }).then((response) => {
          if (response.data.msg == 'success') {
            this.$nextTick(() => {
              response.data.permission.forEach(function ( value,index){
                if(value.permission == '42'){
                  that.addperms = value.departid == that.order.departmentguid ? true : false;
                  return;
                }
              })
            })
          }

        })
      },
      packItems: function(items) {
        let ldata = [];
        items.forEach((item, index, self) => {
          let idata = {};
          if (item.plckcode.length == 3) {
            idata.tit = item.plckitemname;
            idata.list = self.filter(ii => {
              return ii.plckcode.length == 6 && ii.plckcode.substr(0, 3) == item.plckcode;
            })
            console.log('idata:', idata)
            ldata.push(idata);
          }
        })
        return ldata;
      },
      getOrder: async function(id) {
        await this.axios({
          method: 'get',
          url: '/farmer/Farmerorder!detail.action',
          params: {'entity.guid': id}
        }).then((response) => {
          if (response.data.msg == "success") {
            this.order = response.data.farmerorder;
          } else {
            this.toastText("获取订单数据失败");
          }

        })
      },
      getArealands: async function () {
        await this.getOrder(this.$route.query.id);
        this.axios({
          method: 'get',
          url: '/harvest/Procurementcontract!getArealand.action',
          params: {userid: this.order.farmerid}
        }).then(response => {
          if (response.data.msg == 'success') {
            this.arealands = response.data.arealands;
            this.arealand = this.arealands[0] || '';
          } else {
            this.toastText('获取地块数据失败')
          }
        });
      },
      getPlcks: function() {
        $.showLoading("加载中");
        this.axios({
          method: 'get',
          url: '/farmer/Plantcheck!viewAll.action',
          params: {}
        }).then((response) => {
          if (response.data.msg == 'success') {
            this.plcks = response.data.result.filter(item => {
              return this.existPlcks.indexOf(item.guid) == -1;
            });
          } else {
            this.toastError("系统错误");
          }
          $.hideLoading();
        })
      },
      getRecords: function (orderid, areaid) {
        this.postParams.pageNo = 1;
        this.postParams.pageSize = 10;
        this.postParams.functiontype = 24;
        this.postParams['entity.orderid'] = orderid;
        this.postParams['entity.arealandid'] = areaid;
        this.axios({
          method: 'get',
          url: '/farmer/Pcrecord!page.action',
          params: this.postParams
        }).then(response => {
          if (response.data.msg == 'success') {
            this.records = response.data.pagelist.rows;

            this.existPlcks = [];
            this.records.forEach(item =>{
              this.existPlcks.push(item.plckkid);
            })
          } else {
            this.toastText('获取田检记录数据失败')
          }
        });
      },
      addItem: function() {
        if (this.arealand == '') {
          this.toastText('请先选择地块');
          return;
        }
        this.$router.push({name: 'AddCheckRecord', query: {id: this.id, arealand: this.arealand, existPlcks: this.existPlcks}});
      },
      editItem: function (guid) {
        this.$router.push({name: 'EditCheckRecord', query: {id: this.id, arealand: this.arealand, existPlcks: this.existPlcks, recordid: guid}});
      },
      delItem: function (guid) {
        let that = this;
        $.confirm('确定要删除？', function () {
          that.axios({
            method: 'post',
            url: '/farmer/Pcrecord!del.action',
            params: {'entity.guid': guid}
          }).then(response =>{
            if (response.data.msg == 'success') {
              that.getRecords(that.order.guid, that.arealand.guid);
            } else {
              that.toastError("系统错误");
            }
          })
        })
      }
    }
  };
</script>
